package com.taiji.dicom4cloud.smart.alarm.socket;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Description
 * @Author fanxl
 * @Date 2021/8/16
 **/
@Slf4j
public class ServerSocketBean implements Runnable {

    private ExecutorService threadPool = Executors.newCachedThreadPool();

    /**
     * socket 服务
     */
    private ServerSocket server;

    @Override
    public void run() {
        try {
            server = new ServerSocket(8899);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(ObjectUtil.isNotNull(server)){
            while (true) {
                try {
                    Socket socket = server.accept();
                    System.out.println("连接客户端地址：" + socket.getRemoteSocketAddress());
                    System.out.println("connected...");
                    ClientHandler clientHandler = new ClientHandler(socket);
                    threadPool.submit(clientHandler);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info("Socket 服务异常：{}",e.getMessage());
                }
            }
        }

    }
}
